<template>
    <view class="coupon_detail_page">
        <CouponDetail
            v-if="Data.id"
            :disabled="buttonName !== '立即领取'"
            :Data="Data"
            @comfirm="acquireCouponHandler"
            :btnName="buttonName"></CouponDetail>
        <view v-else class="none-end">
            <img class="empty" :src="getImgOssUrl('/ui-prod-2.3.0/empty-addr@2x.png')" />
            暂无数据~
        </view>
        <Loading />
    </view>
</template>
<script setup>
import CouponDetail from '@/components/coupon/detail.vue';
import Loading from '@/components/el-loading';
import router from '@/router';
import { ref, reactive, onMounted, computed } from 'vue';
import { getParamsBySceneHook } from '@/hooks';
import request from '@/request';
import { checkToken, getImgOssUrl } from '@/commons/utils';
import storage from '@/commons/storage';
import { useTrace } from '@/commons/trace';
import subscribe from '@/commons/subscribe';
import { onShow } from '@dcloudio/uni-app';
const { traceReport } = useTrace();
const props = defineProps({
    couponId: {
        type: [String, Number],
        default: ''
    },
    shopId: {
        type: [String, Number],
        default: ''
    },
    scene: {
        type: String,
        default: ''
    }
});

const params = reactive({
    shopId: '',
    couponId: ''
});

const Data = reactive({
    // 优惠券类型 1-满减、2-折扣
    couponType: null,
    // 优惠券标题
    couponTitle: null,
    // 优惠券描述
    couponDescription: null,
    // 每满即减 1-否、2-是
    couponEveryDecrease: 1
});

const buttonName = computed(() => {
    let name = '立即领取';
    if (Number(Data.couponStatus) === 3) {
        name = '优惠券已失效';
    }
    if (Number(Data.couponStatus) === 4) {
        name = '优惠券已过期';
    }
    if (Data.couponNoStock) {
        name = '优惠券已领完';
    }
    if (Data.acquireLimit) {
        name = '领取已达上限';
    }
    return name;
});

const queryCouponInfo = () => {
    request('queryCouponDetailServ', {
        couponId: params.couponId,
        shopId: params.shopId,
        userId: storage.get('userId') || 0
    }).then(result => {
        const res = result.data;
        Object.assign(Data, res, {
            id: res.id
        });
    });
};

const refeshData = async () => {
    let shopId = '';
    let couponId = '';
    if (props.scene) {
        // 分享弹窗生成的二维码跳转的
        const res = await getParamsBySceneHook(props.scene, 1);
        shopId = res?.shopId;
        couponId = res?.couponId;
    } else if (props.shopId && props.shopId > 0) {
        // 如果参数上带有shopId,比如分享朋友圈，短链，分享给好友的链接
        storage.set('ZW_SHOP_ID', Number(props.shopId));
        shopId = props?.shopId;
        couponId = props?.couponId;
    }
    if (!couponId || !shopId) {
        uni.showToast({
            title: '优惠券不存在',
            icon: 'none'
        });
        setTimeout(function () {
            router.switchTab({
                url: `/pages/tabbar/home`
            });
        }, 1500);
        return;
    }
    params.shopId = shopId;
    params.couponId = couponId;
    queryCouponInfo();
};

const confirmHandler = async () => {
    let res;
    try {
        res = await request('acquireCouponServ', {
            couponId: Data.id
        });
    } catch (e) {
        uni.showToast({
            title: e.data.msg || '网络错误，请稍后重试~',
            icon: 'none'
        });
        queryCouponInfo();
        return;
    }
    if (res.data) {
        traceReport('receive_coupon', { couponId: Data.id, couponName: Data.couponTitle });
        subscribe('getcoupon');
        uni.showModal({
            title: '领取成功',
            content: '恭喜你，已成功领取优惠券',
            showCancel: false,
            confirmText: '确认',
            confirmColor: '#576B95',
            success: () => {
                uni.redirectTo({
                    url: `/pages-user/coupon/detail/index?couponId=${res.data}&userCouponStatus=0`
                });
            }
        });
    }
};

const acquireCouponHandler = async () => {
    if (buttonName.value !== '立即领取') {
        return;
    }
    if (await checkToken()) {
        confirmHandler();
    } else {
        router.push('/pages-user/login/index');
    }
};
onShow(() => {
    refeshData();
});
</script>
<style lang="scss" scoped>
.none-end {
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    font-size: 28rpx;
    color: #333333;
    padding: 342rpx 29rpx 0 29rpx;
    .empty {
        width: 279rpx;
        height: 216rpx;
    }
}
</style>
